package cn.bytepath.org.controller;

import cn.bytepath.org.domain.Department;
import cn.bytepath.org.query.DepartmentQuery;
import cn.bytepath.org.service.IDepartmentService;
import cn.bytepath.util.PageInfo;
import cn.bytepath.util.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门的controller层
 * @author Jack.C
 * @createDate 2022-01-20
 * @version 1.0
 */
@Api(tags = "部门接口",description = "部门接口详细描述")
@RestController
@RequestMapping("/department")
// @CrossOrigin 不用此注解,默认开启所有的服务器都可跨域访问此controller,不安全,需针对性进行属性配置,且每个controller都需配置,比较繁琐
public class DepartmentController {

    /**
     * 注入部门业务层对象
     */
    @Autowired
    private IDepartmentService departmentService;

    @ApiOperation("查询部门的文档树")
    @GetMapping
    public List<Department> getDeptTree() {
        return departmentService.findDeptTree();
    }

    @ApiOperation("高级查询并分页")
    @PostMapping
    public PageInfo<Department> pageQuery(@RequestBody DepartmentQuery query) {
        System.out.println(query);
        return departmentService.findPageInfoByQuery(query);
    }

    @ApiOperation("根据id删除部门对象")
    @DeleteMapping("/{id}")
    public PageResult delete(@PathVariable("id") Long id) {

        try {
            Thread.sleep(2222);
            departmentService.delete(id);
            return PageResult.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PageResult.FAIL.setMsg(e.getMessage());
        }
    }

    @ApiOperation("根据id批量删除部门对象")
    @PatchMapping
    public PageResult deleteBatch(@RequestBody Long[] ids) {

        try {
            departmentService.deleteBatch(ids);
            return PageResult.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PageResult.FAIL.setMsg(e.getMessage());
        }
    }

    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    @PutMapping
    public PageResult saveOrUpdate(@RequestBody Department department) {
        try {
            departmentService.saveOrUpdate(department);
            return PageResult.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PageResult.FAIL.setMsg(e.getMessage());
        }
    }
}
